import axios from "axios";
import { Message } from "view-design";
const baseURL = "http://localhost:3000";
const instance = axios.create();

instance.interceptors.request.use(config => {
  const token = localStorage.getItem("token");
  if (token) {
    config.headers["token"] = token;
  }
  return config;
});
instance.interceptors.response.use(response => {
  return response;
});

function fetch(url, options) {
  return new Promise(resolve => {
    const default_url = baseURL + url;
    options.url = default_url;
    instance(options).then(response => {
      const res = response.data;
      switch (res.code) {
        case 200: // 成功
          resolve(res.data);
          break;
        case 40001: // 成功
          Message.info(res.msg);
          break;
        default:
          Message.info(res.msg);
      }
    });
  });
}

export default {
  post: function(url, options = {}) {
    return fetch(url, {
      method: "POST",
      data: options.data
    });
  },
  get: function(url, options = {}) {
    return fetch(url, {
      method: "GET",
      data: options.data
    });
  },
  delete: function(url, options = {}) {
    return fetch(url, {
      method: "DELETE",
      data: options.data
    });
  },
  file: function(url, data) {
    return fetch({
      headers: {
        "Content-Type": "multipart/form-data"
      },
      url: `${process.env.VUE_APP_API}${url}`,
      method: "POST",
      data
    });
  }
};
